#include <PopupQSqliteDatabase.hpp>
#include <QFile>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QVariant>

using namespace Popup;
using namespace std;

struct MyDatabaseUser : PopupDatabaseUser
{
  unsigned long id;
  string login;
  string iconpath;
  string nickname;
  
  unsigned long getID() const { return id; }
  const std::string & getLogin() const { return login; }
  const std::string & getNickname() const { return nickname; }
  const std::string & getIconPath() const { return iconpath; }
};

PopupQSqliteDatabase::PopupQSqliteDatabase(const string & p_path, 
					   const PopupLoggerUI *p_logger)
  : m_db(QSqlDatabase::addDatabase("QSQLITE")),
    m_logger(p_logger), m_connected(false)
{
  if (!QFile::exists(p_path.c_str())) {
    m_logger->appendLog(POPUP_LOG_INFO, 
			"No such sqlite database: %s. Creating database.",
			p_path.c_str());
  }
  else
  {  
    m_db.setDatabaseName(p_path.c_str());
    if (!m_db.open()) {
      m_logger->appendLog(POPUP_LOG_CRITICAL, 
			  "Oopps!! Cannot open sqlite database %s.",
			  p_path.c_str());
    }
    else {
      m_connected = true;
    }
  }
}

PopupQSqliteDatabase::~PopupQSqliteDatabase()
{
  if ((m_connected == true) && (m_db.isOpen())) {
    m_db.close();
  }
}

PopupDatabaseUser *PopupQSqliteDatabase::connect(const string & p_login,
						 const std::string & p_password,
						 std::string *p_message)
{
  QSqlQuery query;
  query.exec("SELECT * FROM users");
  //query.prepare("SELECT * FROM users WHERE login=\":login\";");
  //query.bindValue(":login", QString(p_login.c_str()));
  //query.exec();
  
  if (query.isActive())
  {
    QSqlRecord record = query.record();
    int idCol       = record.indexOf("id");
    int nnameCol    = record.indexOf("nickname");
    int hashCol     = record.indexOf("hash");
    int iconPathCol = record.indexOf("iconpath");
    
    MyDatabaseUser *databaseUser = new MyDatabaseUser();
    databaseUser->id = query.value(idCol).toUInt();
    printf("id= %d", databaseUser->id);
    databaseUser->login = p_login;
    databaseUser->nickname = query.value(nnameCol).toString().toStdString();
    string hash = query.value(hashCol).toString().toStdString();
    databaseUser->iconpath = query.value(iconPathCol).toString().toStdString();
    return databaseUser;
  }
  else
  {
    m_logger->appendLog(POPUP_LOG_ERROR, "Oops! Fait chier la bite!");
    return NULL;
  }
}

bool PopupQSqliteDatabase::update(const PopupDatabaseUser *p_user)
{
  return false;
}




